<template>
  <a-modal
    v-model:open="openEditSpace"
    title="编辑空间信息"
    ok-text="保存"
    cancel-text="取消"
    @ok="editSpace"
  >
    <a-form layout="horizontal" :model="editSpaceParam" style="max-width: 600px">
      <a-form-item label="空间昵称">
        <a-input v-model:value="editSpaceParam.spaceName" placeholder="输入昵称" allow-clear />
      </a-form-item>

      <a-form-item label="空间级别">
        <a-select
          v-model:value="editSpaceParam.spaceLevel"
          placeholder="选择空间级别"
          :options="SPACE_LEVEL_OPTIONS"
          allow-clear
          @change="spaceLevelShow(editSpaceParam.spaceLevel)"
        >
        </a-select>
      </a-form-item>

      <a-form-item label="空间容量（单位：M）">
        <a-input v-model:value="editSpaceParam.maxSize" placeholder="输入最大空间容量" allow-clear>
        </a-input>
      </a-form-item>

      <a-form-item label="存储数量">
        <a-input v-model:value="editSpaceParam.maxCount" placeholder="输入最大存储数量" allow-clear />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { defineExpose, onMounted, reactive, ref } from 'vue'
import { listSpaceLevelUsingPost, updateSpaceUsingPost } from '@/api/spaceController.ts'
import { message, type UploadProps } from 'ant-design-vue'
import { SPACE_LEVEL_OPTIONS } from '@/constants/space.ts'
import { formatSize } from '@/utils'


// 编辑参数
let editSpaceParam = ref<API.SpaceUpdateRequest>({})

// 获取父组件方法
const emit = defineEmits(['refresh'])

// 打开对话框
const openEditSpace = ref<boolean>(false)
const openDialog = (params: API.SpaceUpdateRequest) => {
  console.log(params)
  editSpaceParam.value = params
  openEditSpace.value = true
}

/**
 *  编辑空间
 */
const editSpace = async () => {
  const res = await updateSpaceUsingPost(editSpaceParam.value)
  if (res.data.code === 0 && res.data.data) {
    editSpaceParam.value = {
      spaceName: '',
      spaceLevel: 0
    }
    openEditSpace.value = false
    message.success('修改成功')
    // 调用父组件的方法
    await emit('refresh')
  } else {
    message.error('修改失败，' + res.data.message)
  }
  openEditSpace.value = false
}


// 获取空间级别

const spaceLevelList = ref<API.SpaceLevel[]>([])
const getSpaceLevelList = async () => {
  const res = await listSpaceLevelUsingPost()
  if (res.data.code === 0 && res.data.data){
    spaceLevelList.value = res.data.data
  }else {
    message.error("加载空间级别失败，" + res.data.message)
  }
}

const spaceLevelShow = (selectSpaceLevel: any) => {
  spaceLevelList.value.map(spaceLevel => {
    if (spaceLevel.value == selectSpaceLevel){
      editSpaceParam.value.maxCount = spaceLevel.maxCount
      editSpaceParam.value.maxSize = spaceLevel.maxSize
    }
  })
}

onMounted(() => {
  getSpaceLevelList()
})

// 暴露方法
defineExpose({
  openDialog,
})
</script>

<style scoped>


</style>
